"ui";
activity.window.addFlags(android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.window.setStatusBarColor(android.graphics.Color.TRANSPARENT);
activity.window.getDecorView().setSystemUiVisibility(android.view.View.SYSTEM_UI_FLAG_LAYOUT_STABLE | android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

var startTime, forwardTime, interval, lastTime, NTPClockOffset, NTPClockDelay;
var autoSelectAll, testModel, isNeedFlash, duration, flushTime;
var window;
//时间工具类
var timeUtils = require('TimeUtils.js');
var color = "#00aaff";
ui.layout(
    <vertical>
    <linear id="appbar" orientation="vertical" h="90">
        <View h="40" w="*"/>
        <frame h="50">
            <img id="back" src="@drawable/ic_arrow_back_black_48dp" padding="12" tint="#ffffff" w="50" h="50" foreground="?selectableItemBackground"/>
            <text id="app_name" textSize="18sp" textStyle="bold" textColor="#ffffff" w="*" text="苏宁购物车模式" h="50" gravity="center"/>
            <text id="app_ms" textSize="14sp" textColor="#ffffff" w="70" layout_gravity="right" text="说明" h="50" gravity="center" foreground="?selectableItemBackground"/>
        </frame>
    </linear>
    <frame h="*">
    <ScrollView>
            <vertical w="*" h="*" padding="10">
            <text h="30" id="networkTest" text="正在检测网络延迟..." gravity="top|left" textColor="red" textSize="13sp" margin="0 5" />
                <horizontal layout_weight="1" margin="0 0 0 5">
                    <Switch textSize="15sp" textColor="black" id="isUseNetTime"  text="网络时间" checked="true" layout_weight="1" padding="0 0 5 0"/>
                    <Switch textSize="15sp" textColor="black" id="autoSelectAll"text="自动全选"  checked="false" layout_weight="1" padding="5 0 0 0"/>
                </horizontal>
                {/* <Switch textSize="15sp" textColor="black" id="testModel" margin="0 0 0 10" text="测试模式"
                    checked="false" /> */}
                <horizontal w="*" h="1sp" margin="0 10 0 20" bg='#E2E2E2'></horizontal>
                <horizontal h="40">
                    <checkbox id="isNeedFlash" text="" textColor="black" textSize="16" />
                    <text textSize="15sp" textColor="black" text="刷新时长" w="auto" h="40" gravity="center"/>
                    <input id="duration" textSize="15sp" textColor="black" inputType="number" w="120" h="40"  text="350" hint="350" padding="10 0 0 0" />
                    <text textSize="15sp"  text="毫秒" textColor="black"  w="auto" h="40"/>
                </horizontal>

                <horizontal w="*" h="1sp" margin="0 10 0 20" bg='#E2E2E2'></horizontal>
                <horizontal >
                    <checkbox id="baseTime" text="倒计时    " w="auto"  h="40" gravity="center" textColor="black" textSize="15" />
                    <horizontal  h="40" layout_weight="1">
                        <text h="40" text="X：" gravity="center" textColor="black" textSize="15"/>
                        <input h="40" id="xp" text="360" hint="360" marginBottom="-6" textSize="15"  w="100" padding="10 0 0 0" layout_weight="1"/>
                        <text h="40" text=" , Y：" gravity="center" textColor="black" textSize="15" />
                        <input h="40" id="yp" text="1250" hint="1250" marginBottom="-6" textSize="15" w="100" padding="10 0 0 0" layout_weight="1"/>
                    </horizontal>
                </horizontal>

                <horizontal w="*" h="1sp" margin="0 10 0 20" bg='#E2E2E2'></horizontal>
                <text textSize="15sp" textColor="black" text="开始时间（年/月/日 时:分:秒）" />
                <horizontal h="50">
                    <input id="startTime" textSize="15sp" textColor="black" padding="10 0 0 0" h="50" inputType="datetime" hint="0" w="0" layout_weight="4" />
                    <button id="selectTimePicker" style="Widget.AppCompat.Button.Colored"  h="50" gravity="center" text="选择" w="0" layout_weight="1" />
                </horizontal>

                <horizontal h="40">
                    <text textSize="15sp" textColor="black" text="提前开始时间" w="auto" h="40" gravity="center"/>
                    <input id="forwardTime" textSize="15sp" textColor="black" inputType="number" w="120" h="40"  text="" hint="0" padding="10 0 0 0" />
                    <text textSize="15sp"  text="毫秒" textColor="black"  w="auto" h="40"/>
                </horizontal>
                <horizontal h="40">
                    <text textSize="15sp" textColor="black" text="提前刷新时间" w="auto" h="40" gravity="center"/>
                    <input id="flushTime" textSize="15sp" textColor="black" inputType="number" w="120" h="40"  text="" hint="0" padding="10 0 0 0" />
                    <text textSize="15sp"  text="毫秒" textColor="black"  w="auto" h="40"/>
                </horizontal>
                <horizontal h="40">
                    <text textSize="15sp" textColor="black" text="提交频率" w="auto" h="40" gravity="center"/>
                    <input id="interval" textSize="15sp" textColor="black" inputType="number" w="120" h="40"  text="" hint="0" padding="10 0 0 0" />
                    <text textSize="15sp"  text="毫秒" textColor="black"  w="auto" h="40"/>
                </horizontal>
                <horizontal h="40">
                    <text textSize="15sp" textColor="black" text="抢购持续时间" w="auto" h="40" gravity="center"/>
                    <input id="lastTime" textSize="15sp" textColor="black" inputType="number" w="120" h="40"  text="" hint="0" padding="10 0 0 0" />
                    <text textSize="15sp"  text="秒" textColor="black"  w="auto" h="40"/>
                </horizontal>

                <vertical h="*" gravity="center">
                    <button id="runSrt" h="40" w="200" bg="#FFF43F3B" textColor="#ffffff"  text="开始运行"  marginTop="20" layout_gravity="center"/>
                </vertical>
            </vertical>
        </ScrollView>
        </frame>
        </vertical>
);

ui.appbar.backgroundDrawable = GradientDrawable("LEFT_RIGHT", ["#FFF43F3B", "#FFEC008C"]);

ui.back.on("click",function(){
    ui.finish();
});
/**
 * 转换成系统支持的颜色
 * @param {颜色} color 
 */
function Color(color) {
    return android.graphics.Color.parseColor(color);
}

/**
 * 配置渐变色
 * @param {方向} orientation 
 * @param {颜色数组} color 
 */
function GradientDrawable(orientation, color) {
    var colors = [];
    color.forEach(color => colors.push(Color(color)));
    return new android.graphics.drawable.GradientDrawable(android.graphics.drawable.GradientDrawable.Orientation[orientation], colors);
}
ui.app_ms.on("click",function(){
    alert("说明", "购物车模式，启动后进去购物车，等到抢购...");
});

//显示倒计时浮窗
ui.baseTime.on("check", function (checked) {
    // 用户勾选无障碍服务的选项时，跳转到页面让用户去开启
    if (checked) {
        timeThread = threads.start(function () {
            var clockOffset = 0;
            if (ui.isUseNetTime.isChecked()) {
                clockOffset = NTPClockOffset;
                // log("================" + NTPClockOffset)
            }
            window = timeUtils.countDownTimeShow(ui.xp.text(), ui.yp.text(), ui.startTime.text(), ui.forwardTime.text(), clockOffset);
        });
    } else if (window) {
        window.close();
        // floaty.closeAll()
        timeThread.interrupt();
    }
});

//校验时间
ui.networkTest.on("click", () => {
    threads.start(function () {
        //重置时间
        threads.start(NTP.sync);
        //刷新延迟
        setTimeout(reflushNetTime, 500);
    });
});

function reflushNetTime() {
    NTPClockOffset = storage.get("NTPClockOffset", "0");
    NTPClockDelay = storage.get("NTPClockDelay", "0");
    if (!NTPClockOffset) {
        NTPClockOffset = 0;
    } else {
        NTPClockOffset = parseInt(NTPClockOffset.split("|")[0]);
    }
    if (NTPClockOffset < 0) {
        var offset_str = "慢了" + -NTPClockOffset + 'ms，'
    } else {
        offset_str = "快了" + NTPClockOffset + 'ms，'
    }
    //网络延迟数据显示
    ui.networkTest.setText("当前设备时间比平台" + offset_str + "网络延迟：" + NTPClockDelay + "ms");
}

// 获取默认开始时间
function getTime() {
    var fmt = "YYYY-MM-dd hh:mm:ss";
    var d = new Date();
    var hh = d.getHours();
    var mm = d.getMinutes();
    if (mm < 30) {
        mm = 30
    } else {
        hh += 1;
        mm = 0
    }
    var o = {
        "Y+": d.getYear() + 1900,
        "M+": d.getMonth() + 1,
        "d+": d.getDate(),
        "h+": hh,
        // "m+": d.getMinutes(),
        // "s+": d.getSeconds()
        "m+": mm,
        "s+": 0
    };
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 4) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    fmt = fmt.replace(/-/g, '/');
    return fmt;
}

// 获取时分秒用于记录日志
function logCommon(msg) {
    console.log(formatDate(getNow()) + " " + msg);
}
function logInfo(msg) {
    console.info(formatDate(getNow()) + " " + msg);
}
function logWarn(msg) {
    console.warn(formatDate(getNow()) + " " + msg);
}
function logError(msg) {
    console.error(formatDate(getNow()) + " " + msg);
}


// 检测网络延迟和时间偏差
var NTP = {
    requiredResponses: 3,
    serverTimes: [],
    serverDelay: [],
    serverUrl: "https://f.m.suning.com/api/ct.do",
    resyncTime: 0, // minutes
    sync: function () {
        var offset = storage.get("NTPClockOffset");
        if (offset) {
            try {
                var t = offset.split("|")[1];
                var d = NTP.fixTime() - parseInt(t, 10);
                if (d < (1000 * 60 * NTP.resyncTime)) {
                    return false;
                }
            } catch (e) {
            }
        }
        NTP.getServerTime();
    },
    getNow: function () {
        var date = new Date();
        return date.getTime();
    },
    parseServerResponse: function (data) {
        var NtpStartTime = storage.get("NtpStartTime");
        var NtpStopTime = NTP.getNow();
        var origtime = parseInt(data.currentTime);
        var delay = ((NtpStopTime - NtpStartTime) / 2);
        var offset = NtpStopTime - origtime - delay;
        NTP.serverTimes.push(offset);
        NTP.serverDelay.push(delay);

        // 因为网络问题，需要多次获取偏移值，获取平均值
        if (NTP.serverTimes.length >= NTP.requiredResponses) {
            var sumOffset = 0;
            var sumDelay = 0;
            var i = 0;
            for (i = 0; i < NTP.serverTimes.length; i++) {
                sumOffset += NTP.serverTimes[i];
                sumDelay += NTP.serverDelay[i];
            }
            var averageOffset = Math.round(sumOffset / i);
            var averageDelay = Math.round(sumDelay / i);
            storage.put("NTPClockOffset", averageOffset + '|' + NTP.fixTime()); // 保存获得offset时的时间戳
            storage.put("NTPClockDelay", averageDelay); // 保存获得offset时的时间戳
        } else {
            NTP.getServerTime();
        }
    },
    getServerTime: function () {
        var NtpStartTime = NTP.getNow();
        storage.put("NtpStartTime", NtpStartTime);

        var res = http.get(NTP.serverUrl);
        if (res.statusCode !== 200) {
            toast("获取网络时间失败: " + res.statusCode + " " + res.statusMessage);
            return false;
        } else {
            NTP.parseServerResponse(res.body.json());
        }
    },
    fixTime: function (timeStamp) {
        if (!timeStamp) {
            timeStamp = NTP.getNow();
        }
        var offset = storage.get("NTPClockOffset");
        try {
            if (!offset) {
                offset = 0;
            } else {
                offset = offset.split("|")[0];
            }
            if (isNaN(parseInt(offset, 10))) {
                return timeStamp;
            }
            return timeStamp + parseInt(offset, 10);
        } catch (e) {
            return timeStamp;
        }
    }
};

// 初始化用户配置
// storage.clear();
var storage = storages.create("sn_cart");
threads.start(NTP.sync);
setTimeout(initConfig, 500);

function initConfig() {
    NTPClockOffset = storage.get("NTPClockOffset", "0");
    NTPClockDelay = storage.get("NTPClockDelay", "0");
    if (!NTPClockOffset) {
        NTPClockOffset = 0;
    } else {
        NTPClockOffset = parseInt(NTPClockOffset.split("|")[0]);
    }
    if (NTPClockOffset < 0) {
        var offset_str = "慢了" + -NTPClockOffset + 'ms，'
    } else {
        offset_str = "快了" + NTPClockOffset + 'ms，'
    }
    ui.networkTest.setText("当前设备时间比平台" + offset_str + "网络延迟：" + NTPClockDelay + "ms");
    ui.startTime.setText(getTime());

    ui.isUseNetTime.checked = storage.get("isUseNetTime", true);

    ui.forwardTime.setText(storage.get("forwardTime", "500").toString());

    ui.interval.setText(storage.get("interval", "100").toString());
    ui.lastTime.setText(storage.get("lastTime", "5").toString());
    ui.xp.setText(storage.get("xp", "360").toString());
    ui.yp.setText(storage.get("yp", "250").toString());

    ui.duration.setText(storage.get("duration", "350").toString());
    ui.flushTime.setText(storage.get("flushTime", "1500").toString());
}

// 检测时间字符串是否有效
function strDateTime(str) {
    var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
    var r = str.match(reg);
    if (r == null) return false;
    var d = new Date(r[1], r[3] - 1, r[4], r[5], r[6], r[7]);
    return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4] && d.getHours() == r[5] && d.getMinutes() == r[6] && d.getSeconds() == r[7]);
}

// 时间戳转时间字符串
function add0(m) {
    return m < 10 ? '0' + m : m
}

function add00(m) {
    if (m < 10) {
        return '00' + m;
    } else if (m < 100) {
        return '0' + m;
    } else {
        return m;
    }
}

function formatDate(needTime) {
    //needTime是整数，否则要parseInt转换
    var time = new Date(parseInt(needTime));
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    var ms = time.getMilliseconds();
    return add0(h) + ':' + add0(mm) + ':' + add0(s) + ":" + add00(ms);
}

// 根据时间偏移值计算真实时间
function getNow() {
    var now = new Date().getTime();
    if (isUseNetTime) {
        return now - NTPClockOffset
    }
    return now
}

// 程序主要逻辑
ui.runSrt.click(function () {
    // 检查无障碍服务
    if (auto.service == null) {
        toast("请先开启无障碍服务！");
        return;
    }

    //运行
    startTime = ui.startTime.getText().toString();
    isUseNetTime = ui.isUseNetTime.isChecked();
    testModel = false;
    isNeedFlash = ui.isNeedFlash.isChecked();;
    autoSelectAll = ui.autoSelectAll.isChecked();
    duration = parseInt(ui.duration.getText());

    forwardTime = parseInt(ui.forwardTime.getText());
    interval = parseInt(ui.interval.getText());
    lastTime = parseInt(ui.lastTime.getText());
    xp = parseInt(ui.xp.getText());
    yp = parseInt(ui.yp.getText());
    flushTime = parseInt(ui.flushTime.getText());
    if (!strDateTime(startTime)) {
        ui.startTime.setError("请输入正确的日期");
        return;
    } else if (forwardTime > 1000) {
        ui.forwardTime.setError("请输入0-1000之间的值");
        return;
    }
    storage.put("isUseNetTime", isUseNetTime);
    storage.put("forwardTime", forwardTime);
    storage.put("interval", interval);
    storage.put("lastTime", lastTime);
    storage.put("xp", xp);
    storage.put("yp", yp);
    storage.put("flushTime", flushTime);
    storage.put("duration", duration);
    // retryTimes = Math.round(lastTime * 1000 / interval);

    if (ui.runSrt.getText().toString() === '开始运行') {
        // 一直保持屏幕常亮
        device.keepScreenOn();
        threads.start(main);
        ui.runSrt.setText('停止运行');
    } else {
        threads.shutDownAll();
        console.hide();
        device.cancelKeepingAwake();
        ui.runSrt.setText('开始运行');
    }
});


function main() {
    //显示控制台
    var middle = device.width / 2 - 400;
    console.setSize(800, 800);
    console.setPosition(middle, 0);
    console.show();

    var carCount = 0;
    var notInCarCount = 0;
    var retryCount = 0;
    var dunCount = 0;
    var susses = 0;
    var loadding = 0;
    var notChecked = 0;
    var backCount = 0;

    logError("脚本开始运行，当前时间偏移: " + NTPClockOffset + " 网络延迟: " + NTPClockDelay);
    var startChecktime = new Date(Date.parse(startTime)).getTime();
    var endTime = new Date(startChecktime.valueOf() + lastTime * 1000).getTime();
    var startChecktimeFix = startChecktime - forwardTime;
    var startFlashTime = startChecktime - flushTime;

    if (isNeedFlash) {
        logInfo("预期开始刷新时间为：" + formatDate(startFlashTime));
    }
    logInfo("预期开始抢购时间为：" + formatDate(startChecktimeFix));
    logInfo("预期结束抢购时间为：" + formatDate(endTime));

    // 检测是否进入购物车
    x = setInterval(function () {
        var t = getNow();
        if (t < startChecktimeFix) {
            if (text("全选").exists()) {
                if (carCount === 0) {
                    logCommon("已进入购物车，请检查需要抢购的商品是否已勾选，并设置好购买数量，脚本将自动结算");
                    carCount++;
                    notInCarCount = 0
                }

            } else {
                if (notInCarCount === 0) {
                    logCommon("未进入购物车，请前往");
                    carCount = 0;
                    notInCarCount++
                }
            }
        } else {
            not_in_car_count = 0;  // 购物车状态复位
            clearInterval(x)
        }

    }, 500);

    var confirmThread = threads.start(function () {
        while (true) {
            var confirm = textContains("确定").findOne();
            logCommon("确认:" + confirm.click());
            sleep(1000);
        }
    });
    var knowThread = threads.start(function () {
        while (true) {
            var confirm = textContains("知道了").findOne();
            logCommon("知道了:" + confirm.click());
            sleep(400);
        }
    });
    var readThread = threads.start(function () {
        while (true) {
            waitForActivity("android.app.Dialog");
            var confirm = textContains("确认").findOne();
            logCommon("确认:" + confirm.click());
            sleep(1000);
        }
    });

    if (autoSelectAll) {
        var selectThread = threads.start(function () {
            //在新线程执行的代码
            while (true) {
                //自动勾选
                var selectAll = className("android.widget.CheckBox").text("全选").enabled(true).checked(false).findOne();
                selectAll.click()
                logCommon("自动全选");
                sleep(100);
            }
        });
    }

    var timeFlush = true;
    z = setInterval(function () {
        var nowTime = getNow();
        var found = false;
        if (isNeedFlash && timeFlush && nowTime >= startFlashTime && nowTime < endTime) {
            timeFlush = false;
            logCommon("开始提前刷新");
            dropDown(duration);
            // className("android.widget.CheckBox").desc("全选").enabled(true).checked(false).findOne().click();
        }
        if (nowTime >= startChecktimeFix && nowTime < endTime) {
            if (retryCount === 0) {
                logInfo("时间到，开始抢购");
            }
            // 如果在购物车页面且已勾选商品
            if (textContains("结算(").exists()) {
                logCommon("去结算");
                if (textContains("结算(").findOne().parent().click()) {
                    var scope = textContains("结算(").findOne().bounds();
                    click(scope.centerX(), scope.centerY())
                }
                notInCarCount = 0;
                found = true;
                // logCommon("去结算");
                if (testModel) {
                    logError(className("android.widget.TextView").text("提交订单").findOne().text() + ",测试不提交...");
                } else {
                    className("android.widget.TextView").text("提交订单").findOne().click();
                    found = true;
                    logInfo("提交订单");
                }
            }

            // 如果在提交订单界面
            else if (className("android.widget.TextView").text("提交订单").exists()) {
                if (testModel) {
                    // className("android.widget.TextView").text("提交订单").findOne().click();
                    logError(className("android.widget.TextView").text("提交订单").findOne().text() + ",测试不提交...");
                    found = true;
                } else {
                    className("android.widget.TextView").text("提交订单").findOne().click();
                    found = true;
                    logInfo("提交订单");
                }
            }

            // 如果加载中
            else if (className("android.widget.TextView").textContains("加载中").exists()) {
                if (loadding === 0) {
                    loadding = 1;
                    logCommon("加载中");
                }
                found = true;
            }

            // 如果已经卖完
            else if (textContains("已售罄").exists() || textContains("卖完了").exists()) {
                logError("已售罄，任务结束");
                clearInterval(z);
                device.cancelKeepingAwake();
                threads.shutDownAll();
            }

            // 抢购成功
            else if (textContains("苏宁收银台").exists() || textContains("订单中心").findOne()) {
                logError("下单成功！请支付！");
                found = true;
                susses++;
                clearInterval(z);
                device.cancelKeepingAwake();
                threads.shutDownAll();
            }

            // 如果都不是
            else if (notInCarCount === 0 && susses === 0 && found === false) {
                logCommon("未检测到相关页面，请前往购物车");
                notInCarCount++;
            }

            retryCount++

        } else if (nowTime >= endTime) {
            logError("超出预定抢购时长，抢购结束");
            device.cancelKeepingAwake();
            clearInterval(z);
            threads.shutDownAll();
        }
    }, interval);
}


/**
 * 下拉滑动
 * @param {*} duration  不能小于350ms
 */
function dropDown(duration) {
    var width = device.width;
    var height = device.height;
    var y1 = height / 2;
    var y2 = height * 3 / 4;
    var x1 = width / 2;
    var x2 = width / 2;
    // log(x1+"|"+y1+"|"+x2+"|"+y2)
    swipe(x1, y1, x2, y2, duration);
    logInfo("刷新");
}
